// 根据音乐风格标签获取歌手（精准匹配）
export function getArtistsByGenreMatch({ genre, limit }) {
  return httpClient.get('/artists/by-genre-match', { genre, limit });
}
/**
 * 音乐平台前端API接口层
 * 基于OpenAPI 3.0规范设计
 */

// 基础配置
// const BASE_URL = 'http://127.0.0.1:4523/m1/6652266-6394890-default';
const BASE_URL = '/api/v1'; // 使用相对路径，由Vite代理处理
const TIMEOUT = 10000;


// HTTP状态码常量
const HTTP_STATUS = {
  OK: 200,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  TOO_MANY_REQUESTS: 429,
  INTERNAL_SERVER_ERROR: 500
};

// 错误码常量
const ERROR_CODES = {
  USER_EXISTS: 1001,
  EMAIL_EXISTS: 1002,
  INVALID_CREDENTIALS: 1003,
  USER_DISABLED: 1004,
  TOKEN_EXPIRED: 1005,
  SONG_NOT_FOUND: 2001,
  VIP_REQUIRED: 2002,
  PLAY_LIMIT_REACHED: 2003,
  PLAYLIST_NOT_FOUND: 3001,
  NO_PERMISSION: 3002,
  UNSUPPORTED_FORMAT: 4001,
  FILE_TOO_LARGE: 4002,
  SERVICE_UNAVAILABLE: 5001
};

/**
 * HTTP请求工具类
 */
class HttpClient {
  constructor(baseURL = BASE_URL, timeout = TIMEOUT) {
    this.baseURL = baseURL;
    this.timeout = timeout;
    this.interceptors = {
      request: [],
      response: []
    };
  }

  /**
   * 添加请求拦截器
   */
  addRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor);
  }

  /**
   * 添加响应拦截器
   */
  addResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor);
  }

  /**
   * 构建请求配置
   */
  buildRequestConfig(config) {
    const defaultConfig = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: this.timeout
    };

    // 添加认证token
    const token = this.getAuthToken();
    if (token) {
      defaultConfig.headers.Authorization = `Bearer ${token}`;
    }

    return { ...defaultConfig, ...config };
  }

  /**
   * 生成请求ID
   */
  generateRequestId() {
    return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  /**
   * 获取认证token
   */
  getAuthToken() {
    return localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
  }

  /**
   * 执行HTTP请求
   */
  async request(config) {
    const requestConfig = this.buildRequestConfig(config);
    
    // 执行请求拦截器
    for (const interceptor of this.interceptors.request) {
      await interceptor(requestConfig);
    }

    try {
      const url = `${this.baseURL}${requestConfig.url}`;
      const response = await fetch(url, {
        method: requestConfig.method,
        headers: requestConfig.headers,
        body: requestConfig.data ? JSON.stringify(requestConfig.data) : undefined,
        signal: AbortSignal.timeout(requestConfig.timeout)
      });

      const result = await response.json();

      // 执行响应拦截器
      for (const interceptor of this.interceptors.response) {
        await interceptor(result);
      }

      if (!response.ok) {
        throw new ApiError(result.code || response.status, result.message || response.statusText, result.data);
      }

      return result;
    } catch (error) {
      if (error instanceof ApiError) {
        throw error;
      }
      throw new ApiError(HTTP_STATUS.INTERNAL_SERVER_ERROR, error.message);
    }
  }

  // HTTP方法快捷方式
  get(url, params = {}, config = {}) {
    const queryString = new URLSearchParams(params).toString();
    const requestUrl = queryString ? `${url}?${queryString}` : url;
    return this.request({ ...config, method: 'GET', url: requestUrl });
  }

  post(url, data = {}, config = {}) {
    return this.request({ ...config, method: 'POST', url, data });
  }

  put(url, data = {}, config = {}) {
    return this.request({ ...config, method: 'PUT', url, data });
  }

  delete(url, config = {}) {
    return this.request({ ...config, method: 'DELETE', url });
  }

  patch(url, data = {}, config = {}) {
    return this.request({ ...config, method: 'PATCH', url, data });
  }
}

/**
 * API错误类
 */
class ApiError extends Error {
  constructor(code, message, data = null) {
    super(message);
    this.name = 'ApiError';
    this.code = code;
    this.data = data;
  }
}

// 创建HTTP客户端实例
const httpClient = new HttpClient();

// 添加通用请求拦截器
httpClient.addRequestInterceptor(async (config) => {
  // 可以在这里添加loading状态
  console.log('Request:', config);
});

// 添加通用响应拦截器
httpClient.addResponseInterceptor(async (response) => {
  // 处理通用响应逻辑
  if (response.code === ERROR_CODES.TOKEN_EXPIRED) {
    // Token过期，清除本地存储并跳转到登录页
    localStorage.removeItem('auth_token');
    sessionStorage.removeItem('auth_token');
    window.location.href = '/login';
  }
});

/**
 * 用户服务API
 */
class UserApi {
  /**
   * 用户注册
   * @param {UserRegisterRequest} userData - 用户注册数据
   * @returns {Promise<ApiResponse<UserRegisterResponse>>}
   */
  async register(userData) {
    return await httpClient.post('/users/register', userData);
  }

  /**
   * 用户登录
   * @param {UserLoginRequest} credentials - 登录凭据
   * @returns {Promise<ApiResponse<UserLoginResponse>>}
   */
  async login(credentials) {
    return await httpClient.post('/users/login', credentials);
  }

  /**
   * 获取用户信息
   * @param {number} userId - 用户ID
   * @returns {Promise<ApiResponse<UserDetailResponse>>}
   */
  async getUserDetail(userId) {
    return await httpClient.get(`/users/${userId}`);
  }

  /**
   * 更新用户信息
   * @param {number} userId - 用户ID
   * @param {UserUpdateRequest} userData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updateUser(userId, userData) {
    return await httpClient.put(`/users/${userId}`, userData);
  }

  /**
   * 修改密码
   * @param {number} userId - 用户ID
   * @param {PasswordChangeRequest} passwordData - 密码数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async changePassword(userId, passwordData) {
    return await httpClient.put(`/users/${userId}/password`, passwordData);
  }

  /**
   * 上传头像
   * @param {number} userId - 用户ID
   * @param {File} file - 头像文件
   * @returns {Promise<ApiResponse<string>>}
   */
  async uploadAvatar(userId, file) {
    const formData = new FormData();
    formData.append('file', file);
    
    return await httpClient.post(`/users/${userId}/avatar`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  }

  /**
   * 开通会员
   * @param {number} userId - 用户ID
   * @param {MembershipSubscribeRequest} membershipData - 会员数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async subscribeMembership(userId, membershipData) {
    return await httpClient.post(`/users/${userId}/membership`, membershipData);
  }

  /**
   * 退出登录
   * @returns {Promise<ApiResponse<void>>}
   */
  async logout() {
    return await httpClient.post('/users/logout');
  }

  /**
   * 获取用户收藏
   * @param {number} userId - 用户ID
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<any>>>}
   */
  async getUserCollections(userId, params = {}) {
    return await httpClient.get(`/users/${userId}/collections`, params);
  }

  /**
   * 关注用户/歌手
   * @param {number} userId - 用户ID
   * @param {Object} followData - 关注数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async followTarget(userId, followData) {
    return await httpClient.post(`/users/${userId}/follow`, followData);
  }

  /**
   * 取消关注
   * @param {number} userId - 用户ID
   * @param {Object} unfollowData - 取消关注数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async unfollowTarget(userId, unfollowData) {
    return await httpClient.delete(`/users/${userId}/follow`, { data: unfollowData });
  }

  /**
   * 获取关注列表
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<any>>>}
   */
  async getFollowing(userId, pageParams = {}) {
    return await httpClient.get(`/users/${userId}/following`, pageParams);
  }

  /**
   * 获取粉丝列表
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<any>>>}
   */
  async getFollowers(userId, pageParams = {}) {
    return await httpClient.get(`/users/${userId}/followers`, pageParams);
  }
}

/**
 * 歌手服务API
 */
class ArtistApi {
  /**
   * 搜索歌手
   * @param {ArtistSearchRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<ArtistListItem>>>}
   */
  async searchArtists(searchParams) {
    return await httpClient.get('/artists/search', searchParams);
  }

  /**
   * 获取歌手详情
   * @param {number} artistId - 歌手ID
   * @returns {Promise<ApiResponse<ArtistDetailResponse>>}
   */
  async getArtistDetail(artistId) {
    return await httpClient.get(`/artists/${artistId}`);
  }

  /**
   * 获取歌手歌曲列表
   * @param {number} artistId - 歌手ID
   * @returns {Promise<ApiResponse<PageResult<SongListItem>>>}
   */
  async getArtistSongs(artistId) {
    return await httpClient.get(`/songs/artist/${artistId}`);
  }

  /**
   * 获取歌手专辑列表（新版接口）
   * @param {number} artistId - 歌手ID
   * @param {object} pageParams - 分页参数
   * @returns {Promise<ApiResponse<Array<AlbumListItem>>>}
   */
  async getArtistAlbums(artistId, pageParams) {
    // 新接口路径为 /albums/artist/{artistId}
    return await httpClient.get(`/albums/artist/${artistId}`, pageParams);
  }

  /**
   * 按音乐风格获取歌手列表
   * @param {ArtistByGenreRequest} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<ArtistListItem>>>}
   */
  async getArtistsByGenre(params) {
    return await httpClient.get('/api/artist/lists', params);
  }

  /**
   * 获取热门歌手
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<ArtistListItem>>>}
   */
  async getHotArtists(pageParams) {
    return await httpClient.get('/artists/hot', pageParams);
  }

  /**
   * 获取新人歌手
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<ArtistListItem>>>}
   */
  async getNewArtists(pageParams) {
    return await httpClient.get('/artists/new', pageParams);
  }

  // ========== 管理员专用接口 ==========

  /**
   * 创建歌手（管理员）
   * @param {ArtistCreateRequest} artistData - 歌手数据
   * @returns {Promise<ApiResponse<{ artistId: number }>>}
   */
  async createArtist(artistData) {
    return await httpClient.post('/admin/artists', artistData);
  }

  /**
   * 更新歌手信息（管理员）
   * @param {number} artistId - 歌手ID
   * @param {ArtistUpdateRequest} artistData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updateArtist(artistId, artistData) {
    return await httpClient.put(`/admin/artists/${artistId}`, artistData);
  }

  /**
   * 删除歌手（管理员）
   * @param {number} artistId - 歌手ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteArtist(artistId) {
    return await httpClient.delete(`/admin/artists/${artistId}`);
  }

  /**
   * 批量删除歌手（管理员）
   * @param {number[]} artistIds - 歌手ID列表
   * @returns {Promise<ApiResponse<void>>}
   */
  async batchDeleteArtists(artistIds) {
    return await httpClient.delete('/admin/artists/batch', { data: { artistIds } });
  }

  /**
   * 获取歌手管理列表（管理员）
   * @param {ArtistSearchRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<ArtistListItem>>>}
   */
  async getArtistManageList(searchParams) {
    return await httpClient.get('/admin/artists', searchParams);
  }

  /**
   * 启用/禁用歌手（管理员）
   * @param {number} artistId - 歌手ID
   * @param {number} status - 状态：0-禁用,1-启用
   * @returns {Promise<ApiResponse<void>>}
   */
  async toggleArtistStatus(artistId, status) {
    return await httpClient.put(`/admin/artists/${artistId}/status`, { status });
  }
}

/**
 * 音乐服务API
 */
class MusicApi {
  /**
   * 全局搜索（歌曲/歌手/专辑）
   * @param {Object} params - 查询参数 { keyword, limit }
   * @returns {Promise<ApiResponse<Object>>}
   */
  async globalSearch(params) {
    return await httpClient.get('/songs/global-search', params);
  }
  /**
   * 搜索歌曲
   * @param {SongSearchRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<SongListItem>>>}
   */
  async searchSongs(searchParams) {
    return await httpClient.get('/songs/search', searchParams);
  }

  /**
   * 获取歌曲详情
   * @param {number} songId - 歌曲ID
   * @returns {Promise<ApiResponse<SongDetailResponse>>}
   */
  async getSongDetail(songId) {
    return await httpClient.get(`/songs/${songId}`);
  }

  /**
   * 播放歌曲
   * @param {SongPlayRequest} playData - 播放数据，包含songId
   * @returns {Promise<ApiResponse<SongPlayResponse>>}
   */
  async playSong(playData) {
    const { songId, ...otherData } = playData;
    return await httpClient.post(`/songs/${songId}/play`, otherData);
  }

  /**
   * 获取歌曲歌词
   * @param {number} songId - 歌曲ID
   * @returns {Promise<ApiResponse<string>>}
   */
  async getSongLyrics(songId) {
    return await httpClient.get(`/songs/${songId}/lyrics`);
  }

  /**
   * 获取热门歌曲
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<SongListItem>>>}
   */
  async getHotSongs(pageParams) {
    return await httpClient.get('/songs/hot', pageParams);
  }

  /**
   * 获取新歌
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<SongListItem>>>}
   */
  async getNewSongs(pageParams) {
    return await httpClient.get('/songs/new', pageParams);
  }

  /**
   * 获取推荐歌曲
   * @param {Object} params - 推荐参数
   * @returns {Promise<ApiResponse<SongListItem[]>>}
   */
  async getRecommendations(params) {
    return await httpClient.get('/songs/recommendations', params);
  }
}

/**
 * 专辑服务API
 */
class AlbumApi {
  /**
   * 搜索专辑
   * @param {AlbumSearchRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<AlbumListItem>>>}
   */
  async searchAlbums(searchParams) {
    return await httpClient.get('/albums/search', searchParams);
  }

  /**
   * 获取专辑详情
   * @param {number} albumId - 专辑ID
   * @returns {Promise<ApiResponse<AlbumDetailResponse>>}
   */
  async getAlbumDetail(albumId) {
    return await httpClient.get(`/albums/${albumId}`);
  }

  /**
   * 按音乐风格获取专辑列表
   * @param {AlbumByGenreRequest} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<AlbumListItem>>>}
   */
  async getAlbumsByGenre(params) {
    return await httpClient.get('/albums/by-genre', params);
  }

  /**
   * 获取热门专辑
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<AlbumListItem>>>}
   */
  async getHotAlbums(pageParams) {
    return await httpClient.get('/albums/hot', pageParams);
  }

  /**
   * 获取新专辑
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<AlbumListItem>>>}
   */
  async getNewAlbums(pageParams) {
    return await httpClient.get('/albums/new', pageParams);
  }

  // ========== 管理员专用接口 ==========

  /**
   * 创建专辑（管理员）
   * @param {AlbumCreateRequest} albumData - 专辑数据
   * @returns {Promise<ApiResponse<{ albumId: number }>>}
   */
  async createAlbum(albumData) {
    return await httpClient.post('/admin/albums', albumData);
  }

  /**
   * 更新专辑信息（管理员）
   * @param {number} albumId - 专辑ID
   * @param {AlbumUpdateRequest} albumData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updateAlbum(albumId, albumData) {
    return await httpClient.put(`/admin/albums/${albumId}`, albumData);
  }

  /**
   * 删除专辑（管理员）
   * @param {number} albumId - 专辑ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteAlbum(albumId) {
    return await httpClient.delete(`/admin/albums/${albumId}`);
  }

  /**
   * 批量删除专辑（管理员）
   * @param {number[]} albumIds - 专辑ID列表
   * @returns {Promise<ApiResponse<void>>}
   */
  async batchDeleteAlbums(albumIds) {
    return await httpClient.delete('/admin/albums/batch', { data: { albumIds } });
  }

  /**
   * 获取专辑管理列表（管理员）
   * @param {AlbumSearchRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<AlbumListItem>>>}
   */
  async getAlbumManageList(searchParams) {
    return await httpClient.get('/admin/albums', searchParams);
  }

  /**
   * 启用/禁用专辑（管理员）
   * @param {number} albumId - 专辑ID
   * @param {number} status - 状态：0-禁用,1-启用
   * @returns {Promise<ApiResponse<void>>}
   */
  async toggleAlbumStatus(albumId, status) {
    return await httpClient.put(`/admin/albums/${albumId}/status`, { status });
  }
}

/**
 * 用户管理服务API（管理员专用）
 */
class UserManageApi {
  /**
   * 获取用户管理列表（管理员）
   * @param {UserListRequest} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<UserDetailResponse>>>}
   */
  async getUserList(searchParams) {
    return await httpClient.get('/admin/users', searchParams);
  }

  /**
   * 禁用/启用用户（管理员）
   * @param {number} userId - 用户ID
   * @param {UserManageRequest} manageData - 管理数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async manageUser(userId, manageData) {
    return await httpClient.put(`/admin/users/${userId}/manage`, manageData);
  }

  /**
   * 删除用户（管理员）
   * @param {number} userId - 用户ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteUser(userId) {
    return await httpClient.delete(`/admin/users/${userId}`);
  }

  /**
   * 批量删除用户（管理员）
   * @param {number[]} userIds - 用户ID列表
   * @returns {Promise<ApiResponse<void>>}
   */
  async batchDeleteUsers(userIds) {
    return await httpClient.delete('/admin/users/batch', { data: { userIds } });
  }

  /**
   * 重置用户密码（管理员）
   * @param {number} userId - 用户ID
   * @param {string} newPassword - 新密码
   * @returns {Promise<ApiResponse<void>>}
   */
  async resetUserPassword(userId, newPassword) {
    return await httpClient.put(`/admin/users/${userId}/password`, { newPassword });
  }

  /**
   * 强制设置用户会员（管理员）
   * @param {number} userId - 用户ID
   * @param {Object} membershipData - 会员数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async setUserMembership(userId, membershipData) {
    return await httpClient.put(`/admin/users/${userId}/membership`, membershipData);
  }
}

/**
 * 内容管理服务API（管理员专用）
 */
class ContentManageApi {
  // ========== 歌曲管理 ==========

  /**
   * 创建歌曲（管理员）
   * @param {Object} songData - 歌曲数据
   * @returns {Promise<ApiResponse<{ songId: number }>>}
   */
  async createSong(songData) {
    return await httpClient.post('/admin/songs', songData);
  }

  /**
   * 更新歌曲信息（管理员）
   * @param {number} songId - 歌曲ID
   * @param {Object} songData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updateSong(songId, songData) {
    return await httpClient.put(`/admin/songs/${songId}`, songData);
  }

  /**
   * 删除歌曲（管理员）
   * @param {number} songId - 歌曲ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteSong(songId) {
    return await httpClient.delete(`/admin/songs/${songId}`);
  }

  /**
   * 批量删除歌曲（管理员）
   * @param {number[]} songIds - 歌曲ID列表
   * @returns {Promise<ApiResponse<void>>}
   */
  async batchDeleteSongs(songIds) {
    return await httpClient.delete('/admin/songs/batch', { data: { songIds } });
  }

  /**
   * 获取歌曲管理列表（管理员）
   * @param {Object} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getSongManageList(searchParams = {}) {
    return await httpClient.get('/admin/songs', searchParams);
  }

  /**
   * 审核歌曲（管理员）
   * @param {number} songId - 歌曲ID
   * @param {number} status - 审核状态：1-通过,0-拒绝
   * @param {string} [reason] - 拒绝原因
   * @returns {Promise<ApiResponse<void>>}
   */
  async auditSong(songId, status, reason) {
    return await httpClient.put(`/admin/songs/${songId}/audit`, { status, reason });
  }

  // ========== 评论管理 ==========

  /**
   * 获取评论管理列表（管理员）
   * @param {Object} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getCommentManageList(searchParams = {}) {
    return await httpClient.get('/admin/comments', searchParams);
  }

  /**
   * 删除评论（管理员）
   * @param {number} commentId - 评论ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteAdminComment(commentId) {
    return await httpClient.delete(`/admin/comments/${commentId}`);
  }

  /**
   * 管理评论（管理员）
   * @param {number} commentId - 评论ID
   * @param {Object} manageData - 管理数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async manageComment(commentId, manageData) {
    return await httpClient.put(`/admin/comments/${commentId}/manage`, manageData);
  }

  // ========== 动态管理 ==========

  /**
   * 获取动态管理列表（管理员）
   * @param {Object} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getDynamicManageList(searchParams = {}) {
    return await httpClient.get('/admin/dynamics', searchParams);
  }

  /**
   * 删除动态（管理员）
   * @param {number} dynamicId - 动态ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteAdminDynamic(dynamicId) {
    return await httpClient.delete(`/admin/dynamics/${dynamicId}`);
  }

  /**
   * 管理动态（管理员）
   * @param {number} dynamicId - 动态ID
   * @param {Object} manageData - 管理数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async manageDynamic(dynamicId, manageData) {
    return await httpClient.put(`/admin/dynamics/${dynamicId}/manage`, manageData);
  }

  // ========== 播放列表管理 ==========

  /**
   * 获取播放列表管理列表（管理员）
   * @param {Object} searchParams - 搜索参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getPlaylistManageList(searchParams = {}) {
    return await httpClient.get('/admin/playlists', searchParams);
  }

  /**
   * 删除播放列表（管理员）
   * @param {number} playlistId - 播放列表ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteAdminPlaylist(playlistId) {
    return await httpClient.delete(`/admin/playlists/${playlistId}`);
  }

  /**
   * 管理播放列表（管理员）
   * @param {number} playlistId - 播放列表ID
   * @param {Object} manageData - 管理数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async managePlaylist(playlistId, manageData) {
    return await httpClient.put(`/admin/playlists/${playlistId}/manage`, manageData);
  }

  /**
   * 设置推荐播放列表（管理员）
   * @param {number} playlistId - 播放列表ID
   * @param {boolean} isRecommended - 是否推荐
   * @returns {Promise<ApiResponse<void>>}
   */
  async setPlaylistRecommended(playlistId, isRecommended) {
    return await httpClient.put(`/admin/playlists/${playlistId}/recommend`, { isRecommended });
  }
}

/**
 * 播放列表服务API
 */
class PlaylistApi {
  /**
   * 创建播放列表
   * @param {Object} playlistData - 播放列表数据
   * @returns {Promise<ApiResponse<{ playlistId: number }>>}
   */
  async createPlaylist(playlistData) {
    return await httpClient.post('/playlists', playlistData);
  }

  /**
   * 获取播放列表详情（新接口，路径为 /playlists/{playlistId}）
   * @param {number} playlistId - 播放列表ID
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getPlaylistDetailById(playlistId) {
    return await httpClient.get(`/playlists/${playlistId}`);
  }

  /**
   * 获取歌单中的歌曲列表
   * @param {number} playlistId - 播放列表ID
   * @returns {Promise<ApiResponse<Array<Object>>>}
   */
  async getPlaylistSongs(playlistId) {
    return await httpClient.get(`/playlists/${playlistId}/songs`);
  }

  /**
   * 根据标签获取歌单
   * @param {Object} params - 查询参数 { tag: string, page: number, size: number }
   * @returns {Promise<ApiResponse<PageResult<PlaylistItem>>>}
   */
  async getPlaylistsByTag(params = {}) {
    return await httpClient.get('/playlists/by-tag', params);
  }
    /**
   * 获取歌单分类标签
   * @returns {Promise<ApiResponse<Array<{id: number, name: string, code: string}>>>}
   */
    async getPlaylistCategories() {
      return await httpClient.get('/playlists/tags');
    }
  
  // 保留原有分类接口，便于兼容
  async getPlaylistsByCategory(params = {}) {
    return await httpClient.get('/playlists/by-category', params);
  }
  
  /**
   * 更新播放列表
   * @param {number} playlistId - 播放列表ID
   * @param {Object} playlistData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updatePlaylist(playlistId, playlistData) {
    return await httpClient.put(`/playlists/${playlistId}`, playlistData);
  }

  /**
   * 删除播放列表
   * @param {number} playlistId - 播放列表ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deletePlaylist(playlistId) {
    return await httpClient.delete(`/playlists/${playlistId}`);
  }

  /**
   * 添加歌曲到播放列表
   * @param {number} playlistId - 播放列表ID
   * @param {Object} songData - 歌曲数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async addSongsToPlaylist(playlistId, songData) {
    return await httpClient.put(`/playlists/${playlistId}/songs`, songData);
  }

  /**
   * 从播放列表移除歌曲
   * @param {number} playlistId - 播放列表ID
   * @param {number} songId - 歌曲ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async removeSongFromPlaylist(playlistId, songId) {
    return await httpClient.delete(`/playlists/${playlistId}/songs/${songId}`);
  }

  /**
   * 获取用户播放列表
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getUserPlaylists(userId, pageParams = {}) {
    return await httpClient.get(`/playlists/user/${userId}`, pageParams);
  }

  /**
   * 获取公开播放列表
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getPublicPlaylists(pageParams = {}) {
    return await httpClient.get('/playlists/public', pageParams);
  }
}

/**
 * 收藏服务API
 */
class CollectionApi {
  /**
   * 添加收藏
   * @param {Object} collectionData - 收藏数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async addCollection(collectionData) {
    return await httpClient.post('/collections', collectionData);
  }

  /**
   * 取消收藏
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @returns {Promise<ApiResponse<void>>}
   */
  async removeCollection(targetId, targetType) {
    return await httpClient.delete(`/collections/${targetType}/${targetId}`);
  }

  /**
   * 获取收藏列表
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getCollections(params = {}) {
    return await httpClient.get('/collections', params);
  }

  /**
   * 检查收藏状态
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @returns {Promise<ApiResponse<{ isCollected: boolean }>>}
   */
  async checkCollectionStatus(targetId, targetType) {
    return await httpClient.get(`/collections/${targetType}/${targetId}/status`);
  }
}

/**
 * 推荐服务API
 */
class RecommendApi {
  /**
   * 获取个性化推荐
   * @param {Object} params - 推荐参数
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getPersonalRecommendations(params = {}) {
    return await httpClient.get('/recommendations/personal', params);
  }

  /**
   * 获取每日推荐
   * @param {Object} params - 推荐参数
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getDailyRecommendations(params = {}) {
    return await httpClient.get('/recommendations/daily', params);
  }

  /**
   * 获取相似推荐
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @param {Object} params - 推荐参数
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getSimilarRecommendations(targetId, targetType, params = {}) {
    return await httpClient.get(`/recommendations/similar/${targetType}/${targetId}`, params);
  }
}

/**
 * 排行榜服务API
 */
class RankingApi {
  /**
   * 获取热门榜单
   * @param {string} rankingType - 榜单类型
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getRankings(rankingType, params = {}) {
    return await httpClient.get(`/rankings/${rankingType}`, params);
  }

  /**
   * 获取榜单列表
   * @returns {Promise<ApiResponse<Object[]>>}
   */
  async getRankingList() {
    return await httpClient.get('/rankings');
  }

  /**
   * 获取榜单详情
   * @param {string} rankingType - 榜单类型
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getRankingDetail(rankingType) {
    return await httpClient.get(`/rankings/${rankingType}/detail`);
  }
}

/**
 * 社交功能API
 */
class SocialApi {
  /**
   * 关注用户/歌手
   * @param {Object} followData - 关注数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async follow(followData) {
    return await httpClient.post('/social/follow', followData);
  }

  /**
   * 取消关注
   * @param {Object} unfollowData - 取消关注数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async unfollow(unfollowData) {
    return await httpClient.delete('/social/follow', { data: unfollowData });
  }

  /**
   * 获取关注列表
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getFollowingList(userId, pageParams = {}) {
    return await httpClient.get(`/social/following/${userId}`, pageParams);
  }

  /**
   * 获取粉丝列表
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getFollowersList(userId, pageParams = {}) {
    return await httpClient.get(`/social/followers/${userId}`, pageParams);
  }

  /**
   * 检查关注状态
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @returns {Promise<ApiResponse<{ isFollowing: boolean }>>}
   */
  async checkFollowStatus(targetId, targetType) {
    return await httpClient.get(`/social/follow/status/${targetType}/${targetId}`);
  }
}

/**
 * 动态服务API
 */
class DynamicApi {
  /**
   * 发布动态
   * @param {Object} dynamicData - 动态数据
   * @returns {Promise<ApiResponse<{ dynamicId: number }>>}
   */
  async createDynamic(dynamicData) {
    return await httpClient.post('/dynamics', dynamicData);
  }

  /**
   * 获取动态列表
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getDynamics(params = {}) {
    return await httpClient.get('/dynamics', params);
  }

  /**
   * 获取动态详情
   * @param {number} dynamicId - 动态ID
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getDynamicDetail(dynamicId) {
    return await httpClient.get(`/dynamics/${dynamicId}`);
  }

  /**
   * 删除动态
   * @param {number} dynamicId - 动态ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteDynamic(dynamicId) {
    return await httpClient.delete(`/dynamics/${dynamicId}`);
  }

  /**
   * 获取用户动态
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getUserDynamics(userId, pageParams = {}) {
    return await httpClient.get(`/dynamics/user/${userId}`, pageParams);
  }

  /**
   * 获取关注的人的动态
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getFollowingDynamics(pageParams = {}) {
    return await httpClient.get('/dynamics/following', pageParams);
  }
}

/**
 * 评论服务API
 */
class CommentApi {
  /**
   * 发表评论
   * @param {Object} commentData - 评论数据
   * @returns {Promise<ApiResponse<{ commentId: number }>>}
   */
  async createComment(commentData) {
    return await httpClient.post('/comments', commentData);
  }

  /**
   * 获取评论列表
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getComments(params = {}) {
    return await httpClient.get('/comments', params);
  }

  /**
   * 获取评论详情
   * @param {number} commentId - 评论ID
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getCommentDetail(commentId) {
    return await httpClient.get(`/comments/${commentId}`);
  }

  /**
   * 删除评论
   * @param {number} commentId - 评论ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteComment(commentId) {
    return await httpClient.delete(`/comments/${commentId}`);
  }

  /**
   * 更新评论
   * @param {number} commentId - 评论ID
   * @param {Object} commentData - 更新数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async updateComment(commentId, commentData) {
    return await httpClient.put(`/comments/${commentId}`, commentData);
  }

  /**
   * 获取子评论
   * @param {number} parentId - 父评论ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getSubComments(parentId, pageParams = {}) {
    return await httpClient.get(`/comments/${parentId}/replies`, pageParams);
  }
}

/**
 * 点赞服务API
 */
class LikeApi {
  /**
   * 点赞/取消点赞
   * @param {Object} likeData - 点赞数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async toggleLike(likeData) {
    return await httpClient.post('/likes', likeData);
  }

  /**
   * 检查点赞状态
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @returns {Promise<ApiResponse<{ isLiked: boolean }>>}
   */
  async checkLikeStatus(targetId, targetType) {
    return await httpClient.get(`/likes/${targetType}/${targetId}/status`);
  }

  /**
   * 获取点赞列表
   * @param {number} targetId - 目标ID
   * @param {string} targetType - 目标类型
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getLikeList(targetId, targetType, pageParams = {}) {
    return await httpClient.get(`/likes/${targetType}/${targetId}`, pageParams);
  }

  /**
   * 获取用户点赞记录
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getUserLikes(userId, pageParams = {}) {
    return await httpClient.get(`/likes/user/${userId}`, pageParams);
  }
}

/**
 * 消息服务API
 */
class MessageApi {
  /**
   * 发送私信
   * @param {Object} messageData - 消息数据
   * @returns {Promise<ApiResponse<{ messageId: number }>>}
   */
  async sendMessage(messageData) {
    return await httpClient.post('/messages', messageData);
  }

  /**
   * 获取私信列表
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getMessages(pageParams = {}) {
    return await httpClient.get('/messages', pageParams);
  }

  /**
   * 获取消息详情
   * @param {number} messageId - 消息ID
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getMessageDetail(messageId) {
    return await httpClient.get(`/messages/${messageId}`);
  }

  /**
   * 标记消息为已读
   * @param {number} messageId - 消息ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async markMessageAsRead(messageId) {
    return await httpClient.put(`/messages/${messageId}/read`);
  }

  /**
   * 删除消息
   * @param {number} messageId - 消息ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteMessage(messageId) {
    return await httpClient.delete(`/messages/${messageId}`);
  }

  /**
   * 获取会话列表
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getConversations(pageParams = {}) {
    return await httpClient.get('/messages/conversations', pageParams);
  }

  /**
   * 获取与特定用户的会话
   * @param {number} userId - 用户ID
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getConversationWithUser(userId, pageParams = {}) {
    return await httpClient.get(`/messages/conversations/${userId}`, pageParams);
  }

  /**
   * 获取未读消息数
   * @returns {Promise<ApiResponse<{ unreadCount: number }>>}
   */
  async getUnreadCount() {
    return await httpClient.get('/messages/unread/count');
  }
}

/**
 * 文件上传服务API
 */
class FileApi {
  /**
   * 文件上传
   * @param {FormData} formData - 文件数据
   * @returns {Promise<ApiResponse<{ url: string }>>}
   */
  async uploadFile(formData) {
    return await httpClient.post('/files/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  }

  /**
   * 上传头像
   * @param {File} file - 头像文件
   * @returns {Promise<ApiResponse<{ url: string }>>}
   */
  async uploadAvatar(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', 'avatar');
    return this.uploadFile(formData);
  }

  /**
   * 上传音乐文件
   * @param {File} file - 音乐文件
   * @returns {Promise<ApiResponse<{ url: string }>>}
   */
  async uploadMusic(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', 'music');
    return this.uploadFile(formData);
  }

  /**
   * 上传封面图片
   * @param {File} file - 封面文件
   * @returns {Promise<ApiResponse<{ url: string }>>}
   */
  async uploadCover(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', 'cover');
    return this.uploadFile(formData);
  }

  /**
   * 上传歌词文件
   * @param {File} file - 歌词文件
   * @returns {Promise<ApiResponse<{ url: string }>>}
   */
  async uploadLyric(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', 'lyric');
    return this.uploadFile(formData);
  }

  /**
   * 删除文件
   * @param {string} fileUrl - 文件URL
   * @returns {Promise<ApiResponse<void>>}
   */
  async deleteFile(fileUrl) {
    return await httpClient.delete('/files', { data: { url: fileUrl } });
  }

  /**
   * 获取文件信息
   * @param {string} fileUrl - 文件URL
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getFileInfo(fileUrl) {
    return await httpClient.get('/files/info', { url: fileUrl });
  }
}

/**
 * 系统服务API
 */
class SystemApi {
  /**
   * 获取系统配置
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getSystemConfig() {
    return await httpClient.get('/system/config');
  }

  /**
   * 获取系统状态
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getSystemStatus() {
    return await httpClient.get('/system/status');
  }

  /**
   * 获取版本信息
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getVersionInfo() {
    return await httpClient.get('/system/version');
  }

  /**
   * 健康检查
   * @returns {Promise<ApiResponse<Object>>}
   */
  async healthCheck() {
    return await httpClient.get('/system/health');
  }

  /**
   * 获取公告列表
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getAnnouncements(pageParams = {}) {
    return await httpClient.get('/system/announcements', pageParams);
  }

  /**
   * 获取帮助文档
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getHelpDocs() {
    return await httpClient.get('/system/help');
  }

  /**
   * 反馈问题
   * @param {Object} feedbackData - 反馈数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async submitFeedback(feedbackData) {
    return await httpClient.post('/system/feedback', feedbackData);
  }
}

/**
 * 播放历史API
 */
class PlayHistoryApi {
  /**
   * 添加播放记录
   * @param {Object} playData - 播放数据
   * @returns {Promise<ApiResponse<void>>}
   */
  async addPlayHistory(playData) {
    return await httpClient.post('/play-history', playData);
  }

  /**
   * 获取播放历史
   * @param {PageRequest} pageParams - 分页参数
   * @returns {Promise<ApiResponse<PageResult<Object>>>}
   */
  async getPlayHistory(pageParams = {}) {
    return await httpClient.get('/play-history', pageParams);
  }

  /**
   * 清空播放历史
   * @returns {Promise<ApiResponse<void>>}
   */
  async clearPlayHistory() {
    return await httpClient.delete('/play-history');
  }

  /**
   * 删除单条播放记录
   * @param {number} recordId - 记录ID
   * @returns {Promise<ApiResponse<void>>}
   */
  async deletePlayRecord(recordId) {
    return await httpClient.delete(`/play-history/${recordId}`);
  }

  /**
   * 获取最近播放
   * @param {number} limit - 限制数量
   * @returns {Promise<ApiResponse<Object[]>>}
   */
  async getRecentlyPlayed(limit = 20) {
    return await httpClient.get('/play-history/recent', { limit });
  }

  /**
   * 获取播放统计
   * @param {Object} params - 查询参数
   * @returns {Promise<ApiResponse<Object>>}
   */
  async getPlayStatistics(params = {}) {
    return await httpClient.get('/play-history/statistics', params);
  }
}

// 创建API实例
/**
 * 获取新专辑推荐
 * @param {Object} params - 查询参数（如 { limit: 6 }）
 * @returns {Promise<ApiResponse<Array<Album>>>}
 */
async function getNewAlbums(params = {}) {
  // 新专辑推荐接口路径为 /albums/new
  return await httpClient.get('/albums/new', params);
}
const userApi = new UserApi();
const musicApi = new MusicApi();
const artistApi = new ArtistApi();
const albumApi = new AlbumApi();
const playlistApi = new PlaylistApi();
const collectionApi = new CollectionApi();
const playHistoryApi = new PlayHistoryApi();
const recommendApi = new RecommendApi();
const rankingApi = new RankingApi();
const socialApi = new SocialApi();
const dynamicApi = new DynamicApi();
const commentApi = new CommentApi();
const likeApi = new LikeApi();
const messageApi = new MessageApi();
const fileApi = new FileApi();
const systemApi = new SystemApi();
const userManageApi = new UserManageApi();
const contentManageApi = new ContentManageApi();

// 推荐歌单API调用（适配RecommendedPlaylists.vue组件）
/**
 * 获取推荐歌单
 * @param {Object} params - 查询参数（可选）
 * @returns {Promise<ApiResponse<Object>>}
 */
async function getRecommendedPlaylists(params = {}) {
  // 推荐歌单接口建议为 /playlists/recommended，实际根据后端接口调整
  return await httpClient.get('/playlists/recommended', params);
}

// 获取歌手分类标签（音乐风格）
// 获取歌手分类标签（音乐风格）
export function getArtistGenres() {
  // 新接口路径为 /artists/genres
  return httpClient.get('/artists/genres');
}

// 获取歌手列表（可按风格、地区、字母等筛选，带分页）
export function getArtistList(params) {
  return httpClient.get('/api/artist/list', params);
}

export default {
  userApi,
  musicApi,
  artistApi,
  albumApi,
  playlistApi,
  collectionApi,
  playHistoryApi,
  recommendApi,
  rankingApi,
  socialApi,
  dynamicApi,
  commentApi,
  likeApi,
  messageApi,
  fileApi,
  systemApi,

  // 推荐歌单API
  getRecommendedPlaylists,
  // 新专辑推荐API
  getNewAlbums,

  // 管理员API实例
  userManageApi,
  contentManageApi,

  // 工具类和常量
  HttpClient,
  ApiError,
  HTTP_STATUS,
  ERROR_CODES,

  // HTTP客户端实例
  httpClient
};

// 添加根据专辑获取歌曲的 API 路径
albumApi.getAlbumSongs = function (albumId) {
  return httpClient.request({
    method: "GET",
    url: `/songs/album/${albumId}`,
  });
};
